//
//  RCStreamSocketRequest.m
//  RCNetRequestProject
//
//  Created by kabu on 2017/8/15.
//  Copyright © 2017年 RC. All rights reserved.
//

#import "RCStreamSocketRequest.h"
#import "RCSocketSendSerializationer.h"
#import "RCSocketAcceptSerializationer.h"
@interface RCStreamSocketRequest() <NSStreamDelegate>
@property (nonatomic, strong) NSInputStream *inputStream;
@property (nonatomic, strong) NSOutputStream *outputStream;
@property (nonatomic, readonly) NSMutableData *acceptData;
@property (nonatomic, copy) RCConnectSocketCallBack connectCallBack;
@property (nonatomic, copy) RCServerSocketCallBack serverCallBack;

@end
@implementation RCStreamSocketRequest
- (void) connectIP:(NSString *)ip port:(int )aPort callBack:(RCConnectSocketCallBack)aCallBack{
    self.host=ip;
    self.port = aPort;
    
    if (self.inputStream&&self.outputStream) {
        [self closeStream];
        self.inputStream.delegate=nil;
        self.inputStream=nil;
        self.outputStream.delegate=nil;
        self.outputStream=nil;
    }
    
    CFReadStreamRef readStreamRef;
    CFWriteStreamRef writeStreamRef;
    CFStreamCreatePairWithSocketToHost(Nil, (__bridge CFStringRef)ip, (UInt32)aPort, &readStreamRef, &writeStreamRef);
    self.inputStream=(__bridge NSInputStream*)readStreamRef;
    self.outputStream = (__bridge NSOutputStream*)writeStreamRef;
    self.inputStream.delegate = self;
    self.outputStream.delegate = self;
    //是否关闭或者未开始 关闭
    if (self.inputStream.streamStatus == NSStreamStatusNotOpen||self.inputStream.streamStatus == NSStreamStatusClosed) {
        
    }else{
        [self.inputStream close];
        [self.inputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    }
    if (self.outputStream.streamStatus == NSStreamStatusNotOpen||self.outputStream.streamStatus == NSStreamStatusClosed) {
        
    }else{
        [self.outputStream close];
        [self.outputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    }
    [self.inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [self.outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [self.inputStream open];
    [self.outputStream open];
    
    _connectCallBack=nil;
    _connectCallBack=aCallBack;
}

-(void)setRCServerSocketCallBack:(RCServerSocketCallBack)aCallback{
    _serverCallBack =aCallback;
}
- (NSInteger) write:(id)message{
    NSData *data = [self.senderSerializationer transformMessageToData:message];
    NSInteger len= [self.outputStream write:data.bytes maxLength:data.length];
//    NSLog(@"向服务端发送消息");
    if (len) {
       NSLog(@"向服务端发送消息成功了");
    }else{
        NSLog(@"向服务端发送消息失败了");
    }
    return len;
}

- (NSData*)read:(uint8_t)buf{
    //读取数据并打印
    NSMutableData *data = [[NSMutableData alloc] init];
    
    uint8_t defultbuf[2048];
    NSInteger len = 0;
    len = [self.inputStream read:defultbuf maxLength:2048];
    if (len) {
        [data appendBytes:(const void *)defultbuf length:len];
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"读取的数据 %@", str);
    }else{
        NSLog(@"no buffer");
    }
    return data;
}
- (void) disconnect{
    [self closeStream];
    
}
- (void) closeStream{
    [self.inputStream close];
    [self.outputStream close];
    [self.inputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [self.outputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}
#pragma mark NSStreamDelegate
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
    switch (eventCode) {
        case NSStreamEventOpenCompleted:
        {
            NSLog(@"Socket 被打开成功");
            if (_connectCallBack) {
                _connectCallBack(nil,nil);
            }
        }
            break;
        case NSStreamEventHasBytesAvailable:
        {
            NSLog(@"Socket 有可读取字节");
            uint8_t defultbuf[2048];
            NSData *data=[self read:defultbuf[2048]];
            if (data.length) {
                if (_serverCallBack) {
                    NSData *result=[self.acceptSerializationer transformMessageToResult:data];
                    _serverCallBack(result,nil);
                }
            }
        }
            break;
        case NSStreamEventHasSpaceAvailable:
        {
            NSLog(@"Socket 缓存中可以写入字节");
        }
            break;
        case NSStreamEventEndEncountered:
        {
            NSLog(@"Socket 到达字节流的末尾");
            [self closeStream];
            
        }
            break;
        case NSStreamEventErrorOccurred:
        {
            NSLog(@"客户端连接出现错误");
            if (_connectCallBack) {
                _connectCallBack(nil,[NSError errorWithDomain:@"链接失败" code:NSStreamEventErrorOccurred userInfo:nil]);
            }
            _connectCallBack=nil;
        }
            break;
            
        default:
            break;
    }
}
@end
